import {
  getBopTotalByPage,
  addBop,
  updateBop,
  delBopTotal,
  exportBopTotal,
  getAllProcess,
  getBopTotalById,
} from '@/services/baseData/bopTotal';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Select, Table } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from '@/components/dayjs';
import BopInfo from './bopInfo';
const BopTotal: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  const dateFormat = 'YYYY-MM-DD';
  const [optionsProcess, setoptionsProcess] = useState([]); //下拉框用到

  const [modalVisit2, setModalVisit2] = useState(false); // 查看工序弹窗
  const [thebopcode, setthebopcode] = useState('');

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '工艺路径编号',
      dataIndex: 'bopCode',
      align: 'center',
      sorter: true,
    },
    {
      title: '工艺路径名称',
      dataIndex: 'bopName',
      width: 295,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '启用状态',
      dataIndex: 'isEnabled',
      search: false,
      align: 'center',
      sorter: true,

      render: (text, record, _, action) => {
        return <div>{record.isEnabled == 1 ? '启用' : '禁用'}</div>;
      },
    },
    // {
    //   title: '版本号',
    //   dataIndex: 'versionInfo',
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    //   search: false,
    // },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createTime',
      render: (text, record, _, action) => {
        return dayjs(record.createTime).format(dateFormat);
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 190,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={async () => {
            const result = await getBopTotalById({ id: record.id });
            const processlist: any[] = [];
            result.data.bopInfoList.map((item: any, index: any) => {
              processlist.push({ value: item.processId, label: item.processName });
            });
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              bopCode: record.bopCode,
              bopName: record.bopName,
              isStandard: record.isStandard,
              memo: record.memo,
              reserved: record.reserved,
              versionInfo: record.versionInfo,
              id: record.id,
              // 工艺路径回显，对应的工序code列表
              processIdList: processlist,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="useKey"
          onClick={async () => {
            if (record.isEnabled == 1) {
              // 禁用操作，当前工艺路径已启用
              const bopinfo_result = await getBopTotalById({ id: record.id });
              const processlist: any[] = [];
              bopinfo_result.data.bopInfoList.map((item: any, index: any) => {
                processlist.push(item.processId);
              });
              var obj = Object.create({});
              obj.bopTotalDto = record;
              obj.processIdList = processlist;
              obj.bopTotalDto.isEnabled = 0;
              const result = await updateBop(obj);
              if (result != null) {
                message.success('禁用成功');
                actionRef.current!.reload();
              }
            } else {
              // 启用操作
              const bopinfo_result = await getBopTotalById({ id: record.id });
              // console.log('工序查询',bopinfo_result);
              const processlist: any[] = [];
              bopinfo_result.data.bopInfoList.map((item: any, index: any) => {
                processlist.push(item.processId);
              });
              // console.log('processlist',processlist);
              var obj = Object.create({});
              obj.bopTotalDto = record;
              obj.processIdList = processlist;
              obj.bopTotalDto.isEnabled = 1;
              // console.log(obj,'启用参数');
              const result = await updateBop(obj);
              if (result != null) {
                // console.log(result,'启用接口返回');
                message.success('启用成功');
                actionRef.current!.reload();
              }
            }
          }}
        >
          {record.isEnabled == 0 ? '启用' : '禁用'}
        </a>,
        <a
          key="checkdetailKey"
          onClick={async () => {
            setthebopcode(record.bopCode);
            setModalVisit2(true);
          }}
        >
          查看工序
        </a>,
        // <a
        //   key="deleteKey"
        //   onClick={() => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定要删除吗',
        //       okText: '确认',
        //       cancelText: '取消',
        //       onOk: async () => {
        //         await delBopTotal({ id: record.id });
        //         actionRef.current!.reload();
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          if (res.bopName.length < 20) {
            var obj = Object.create({});
            obj.bopTotalDto = res;
            obj.bopTotalDto.isEnabled = 1;
            obj.processIdList = res.processIdList;
            obj.bopTotalDto.isStandard = '1';
            console.log(obj);
            const result = await addBop(obj);
            if (result.code == '-1') {
              message.error('工艺路径名称重复');
            } else if (result != null) {
              message.success('添加成功');
            }
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current!.reload();
          } else {
            message.warning('工艺路径名称过长');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          if (res.bopName.length < 20) {
            var obj = Object.create({});
            if (Object.getOwnPropertyNames(res.processIdList[0]).length == 2) {
              const process_list_: any[] = [];
              res.processIdList.map((item: any, index: any) => {
                process_list_.push(item.value);
              });
              obj.processIdList = process_list_;
            } else {
              obj.processIdList = res.processIdList;
            }
            obj.bopTotalDto = res;
            obj.bopTotalDto.isStandard = '1';
            console.log(obj);
            const result = await await updateBop(obj);
            if (result != null) {
              message.success('修改成功');
            }
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current!.reload();
          } else {
            message.warning('工艺路径名称过长');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  //获取工序
  const getprocess = async () => {
    const getprocesslist = await getAllProcess(null);
    const processOptionContract = [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.id, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="工艺路径"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 105,
          defaultCollapsed: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportBopTotal({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `BopTotal.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          const result = await getBopTotalByPage({ ...params, sorters: sorters, filters: filters });
          getprocess();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1200, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        width={550}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: '375px' }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="启用状态" name="isEnabled" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="工艺路径编号"
            name="bopCode"
            // rules={[{ required: true, message: '请输入工艺路径编号!' }]}
            hidden={!createOrUpdate}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="工艺路径名称"
            name="bopName"
            rules={[{ required: true, message: '请输入工艺路径名称!' }]}
          >
            {/* <Input allowClear /> */}
            <Input maxLength={20} showCount allowClear />
          </Form.Item>
          {/* <Form.Item
            label="标准BOP"
            name="isStandard"
            rules={[{ required: true, message: '请输入是否标准BOP!' }]}
          >
            <Input placeholder="请输入是或否"/>
          </Form.Item> */}
          {/* <Form.Item
            label="版本号"
            name="versionInfo"
            rules={[{ required: true, message: '请输入版本号!' }]}
            hidden={!createOrUpdate}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item> */}
          <Form.Item
            label="工序选择"
            name="processIdList"
            rules={[{ required: true, message: '请选择工序!' }]}
          >
            <Select
              mode="multiple"
              allowClear
              placeholder="请按照顺序选择工序"
              onChange={(value) => {}}
              options={optionsProcess}
            />
          </Form.Item>
          <Form.Item
            label="备注"
            name="memo"
            // rules={[{ required: true, message: 'Please input your memo!' }]}
          >
            <Input allowClear />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="工序查看"
        width={1200}
        open={modalVisit2}
        // onOk={() => setModalVisit2(false)}
        onCancel={() => {
          setModalVisit2(false);
        }}
        destroyOnClose
        footer={[
          <Button
            key="back"
            onClick={() => {
              setModalVisit2(false);
            }}
          >
            关闭
          </Button>,
        ]}
      >
        <BopInfo bopcode={thebopcode} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default BopTotal;
